/**
 * 校园二手交易平台 - 搜索API服务
 * 提供智能搜索、搜索建议、搜索历史等功能
 */

import BaseService, { ApiResponse, PaginatedResponse } from './baseService';
import {
  SearchParams,
  SearchResult,
  SearchSuggestion,
  SearchHistory,
  SearchSortBy,
  Campus,
  Faculty,
  DEFAULT_SEARCH_PARAMS,
  SearchSuggestionResponse,
} from '../types/search';
import { Product } from '../types/product';
import { generateMockProducts, mockSearchSuggestions, mockSearchHistory } from '../mock/search';

/**
 * 搜索服务类
 */
export class SearchService extends BaseService {
  private useMock: boolean = process.env.NODE_ENV === 'development';
  
  constructor(baseURL?: string) {
    super(baseURL || '/api/search');
  }

  /**
   * 商品搜索
   */
  async searchProducts(params: SearchParams): Promise<SearchResult> {
    const searchParams = { ...DEFAULT_SEARCH_PARAMS, ...params };
    
    if (this.useMock) {
      return this.getMockSearchResults(searchParams);
    }
    
    return this.post<SearchResult>('/products', searchParams);
  }

  /**
   * 获取搜索建议
   */
  async getSearchSuggestions(query: string, campus?: Campus): Promise<SearchSuggestionResponse> {
    if (this.useMock) {
      return this.getMockSearchSuggestions(query, campus);
    }
    
    return this.get<SearchSuggestion>('/suggestions', { query, campus });
  }

  /**
   * 获取热门搜索词
   */
  async getHotSearchKeywords(campus?: Campus): Promise<string[]> {
    if (this.useMock) {
      return this.getMockHotKeywords(campus);
    }
    
    return this.get<string[]>('/hot-keywords', { campus });
  }

  /**
   * 获取搜索历史
   */
  async getSearchHistory(): Promise<SearchHistory[]> {
    if (this.useMock) {
      return this.getMockSearchHistory();
    }
    
    return this.get<SearchHistory[]>('/history');
  }

  /**
   * 清空搜索历史
   */
  async clearSearchHistory(): Promise<void> {
    if (this.useMock) {
      return this.clearMockSearchHistory();
    }
    
    return this.delete<void>('/history');
  }

  /**
   * 获取分类下的商品推荐
   */
  async getCategoryRecommendations(categoryId: string, limit?: number): Promise<Product[]> {
    if (this.useMock) {
      return this.getMockCategoryRecommendations(categoryId, limit);
    }
    
    return this.get<Product[]>('/category-recommendations', { 
      categoryId, 
      limit: limit || 10 
    });
  }

  /**
   * 获取校区热门商品
   */
  async getCampusHotProducts(campus: Campus, limit?: number): Promise<Product[]> {
    if (this.useMock) {
      return this.getMockCampusHotProducts(campus, limit);
    }
    
    return this.get<Product[]>('/campus-hot', { 
      campus, 
      limit: limit || 8 
    });
  }

  /**
   * 获取智能推荐商品（基于用户行为）
   */
  async getSmartRecommendations(userId?: string): Promise<Product[]> {
    if (this.useMock) {
      return this.getMockSmartRecommendations(userId);
    }
    
    return this.get<Product[]>('/smart-recommendations', { userId });
  }

  // ==================== Mock 数据实现 ====================

  private async getMockSearchResults(params: SearchParams): Promise<SearchResult> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    let products = generateMockProducts(100);
    
    // 关键词搜索
    if (params.query) {
      const query = params.query.toLowerCase();
      products = products.filter(product => 
        product.title.toLowerCase().includes(query) ||
        product.description.toLowerCase().includes(query)
      );
    }
    
    // 分类筛选
    if (params.category) {
      products = products.filter(product => product.category === params.category);
    }
    
    // 校区筛选
    if (params.campus) {
      products = products.filter(product => product.campus === params.campus);
    }
    
    // 学院筛选
    if (params.faculty) {
      products = products.filter(product => product.faculty === params.faculty);
    }
    
    // 价格区间筛选
    if (params.minPrice !== undefined) {
      products = products.filter(product => product.price >= params.minPrice!);
    }
    if (params.maxPrice !== undefined) {
      products = products.filter(product => product.price <= params.maxPrice!);
    }
    
    // 排序
    if (params.sortBy) {
      products = this.sortProducts(products, params.sortBy);
    }
    
    // 分页
    const page = params.page || 1;
    const pageSize = params.pageSize || 20;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedProducts = products.slice(startIndex, endIndex);
    
    return {
      products: paginatedProducts,
      total: products.length,
      page,
      pageSize,
      totalPages: Math.ceil(products.length / pageSize),
      query: params.query,
      filters: {
        category: params.category,
        campus: params.campus,
        faculty: params.faculty,
        minPrice: params.minPrice,
        maxPrice: params.maxPrice,
      }
    };
  }

  private async getMockSearchSuggestions(query: string, campus?: Campus): Promise<SearchSuggestion> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    return {
      query,
      suggestions: mockSearchSuggestions.filter(suggestion => 
        suggestion.toLowerCase().includes(query.toLowerCase())
      ).slice(0, 5),
      popularKeywords: this.getMockHotKeywords(campus),
      relatedCategories: ['electronics', 'books', 'clothing']
    };
  }

  private getMockHotKeywords(campus?: Campus): string[] {
    const keywords = [
      '笔记本电脑', 'iPhone', '教材', '考研资料', '运动鞋',
      '耳机', '键盘', '显示器', '专业课书', '考研英语'
    ];
    
    if (campus === 'main') {
      return [...keywords, '主校区教材', '宿舍用品'];
    } else if (campus === 'east') {
      return [...keywords, '东校区二手', '东区自习室'];
    }
    
    return keywords;
  }

  private async getMockSearchHistory(): Promise<SearchHistory[]> {
    await new Promise(resolve => setTimeout(resolve, 150));
    return mockSearchHistory;
  }

  private async clearMockSearchHistory(): Promise<void> {
    await new Promise(resolve => setTimeout(resolve, 100));
    // 在真实环境中，这里会清空历史记录
  }

  private async getMockCategoryRecommendations(categoryId: string, limit: number = 10): Promise<Product[]> {
    await new Promise(resolve => setTimeout(resolve, 250));
    
    const products = generateMockProducts(50).filter(product => 
      product.category === categoryId
    );
    
    return products.slice(0, limit);
  }

  private async getMockCampusHotProducts(campus: Campus, limit: number = 8): Promise<Product[]> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const products = generateMockProducts(30).filter(product => 
      product.campus === campus
    );
    
    return products.slice(0, limit);
  }

  private async getMockSmartRecommendations(userId?: string): Promise<Product[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 基于用户ID的简单推荐逻辑
    if (userId) {
      return generateMockProducts(6).map(product => ({
        ...product,
        title: `${product.title}（为您推荐）`
      }));
    }
    
    return generateMockProducts(6);
  }

  /**
   * 商品排序
   */
  private sortProducts(products: Product[], sortBy: SearchSortBy): Product[] {
    switch (sortBy) {
      case SearchSortBy.PRICE_ASC:
        return [...products].sort((a, b) => a.price - b.price);
      case SearchSortBy.PRICE_DESC:
        return [...products].sort((a, b) => b.price - a.price);
      case SearchSortBy.CREATED_AT_ASC:
        return [...products].sort((a, b) => 
          new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
        );
      case SearchSortBy.CREATED_AT_DESC:
        return [...products].sort((a, b) => 
          new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
        );
      case SearchSortBy.VIEWS_DESC:
        return [...products].sort((a, b) => b.viewCount - a.viewCount);
      case SearchSortBy.FAVORITES_DESC:
        return [...products].sort((a, b) => b.favoriteCount - a.favoriteCount);
      default:
        return products;
    }
  }
}

// 创建搜索服务实例
export const searchService = new SearchService();

export default searchService;